<?php
namespace backend\controllers;
use backend\models\Group;
use backend\models\UserLog;
use Yii;
use yii\web\Controller;
use backend\models\Menu;

class BaseController extends Controller
{   
    // 给视图传参
    public $_view = [];
    public $_v = 20150326;
    public $access = [];
    public $session;
    public $_channel = 'admin,yunying,config,article';
    public $auth = ['', 'user_login', 'user_logout', 'login_logout', 'login_login', 'user_alter-password'];
    public function beforeAction($action)
    {
        header("Content-type:text/html;charset=utf-8");
//        $this->session = Yii::$app->session;
//        // 开启session
//        if(!session_id())
//        {
//            $this->session->open();
//        }
        $method = $this->id.'_'.$action->id;
        if($method=='push_push-status')
            return true;
        if (Yii::$app->user->isGuest && $method!='user_login' && $method!='user_logout' && $method!='login_logout' && $method!='login_login') {
            header('location:/user/login');
            die;
        }

        if(!in_array($method, $this->auth))
        {
            $username = Yii::$app->user->getIdentity()->username;
            $menu = $this->getMenu();
            $this->session[Yii::$app->user->getIdentity()->id] = json_encode($menu);
            Yii::$app->redis->set('menu_'.Yii::$app->user->getIdentity()->id, json_encode($menu));

            if($username == 'admin')
            {
                //Yii::$app->redis->set('channel_all_'.Yii::$app->user->getIdentity()->id, $this->_channel);
                return true;
            }
//            else
//            {
//                $channel = Group::getChannel(Yii::$app->user->getIdentity()->gid);
//
//                if(!Yii::$app->redis->get('channel_'.Yii::$app->user->getIdentity()->id))
//                {
//                    Yii::$app->redis->set('channel_'.Yii::$app->user->getIdentity()->id, $channel);
//                }
//                Yii::$app->redis->set('channel_all_'.Yii::$app->user->getIdentity()->id, $channel);
//            }


             $access = $this->access(Yii::$app->user->getIdentity()->id);

            $this->session[Yii::$app->user->getIdentity()->id] = json_encode($access);
            Yii::$app->redis->set('menu_'.Yii::$app->user->getIdentity()->id, json_encode($access));
                 if(!empty($access['access']))
                 {
                     $aa = $_SERVER['QUERY_STRING'];
                     $controller = '/'.$this->id;
                     
                     $url = '/'.$this->id.'/'.$this->action->id;
                     
                     
                     if($controller == 'version-dow')
                         $url = $url."?".$_SERVER["QUERY_STRING"];
                     //var_dump($access['access']);die;
                     if(in_array($url, $access['access']) || $url = '/index/index')
                     {   
                         return true;
                     }
                     else
                     {
                         if(Yii::$app->request->isAjax){
                             return false;
                         }else {
                             header('location:/no-authority/index');
                             die;
                         }
                     }
                    
                 }
                 
                 
                 
             header('location:/no-authority/index');
             die;
        }
        return true;
    }

    /**
     * 重写render 加个参数
     * @author xi
     * @see \yii\base\Controller::render() @date 2015-3-20
     */
    public function render($view, $params = [])
    {
        $this->_view['v'] = $this->_v;
        $this->_view = array_merge($this->_view,$params);
        if(!empty(Yii::$app->user->getIdentity()->id)){

            $access = Yii::$app->redis->get('menu_' . Yii::$app->user->getIdentity()->id);
            //$access = $this->session[Yii::$app->user->getIdentity()->id];
            $access = json_decode($access,true);

            if(isset($access['menu']))
            {
                $menu = $access['menu'];
            }
            else
            {
                $menu = $access;
            }
            //var_dump($menu);die;
            if(!empty($menu))
                Yii::$app->params['menu'] = $menu;
            else
                Yii::$app->params['menu'] = array();
        }
        return parent::render($view,$this->_view);
    }

    public function menu() {
//        $linksql = "select url,name,parent_id from menu where display=1";
//        $link = Yii::$app->db->createCommand($linksql)->queryAll();
        
        $link = \backend\models\Menu::find()->select(['url','name','parent_id'])->where(['display' => 1])->asArray()->all();
        
//        
//        $menuql = "select * from menu where parent_id=0 order by weight asc";
//        $menu = Yii::$app->db->createCommand($menuql)->queryAll();
        
        $menu = \backend\models\Menu::find()->where(['parent_id' => 0])->orderBy("weight asc")->asArray()->all();
        
        foreach ($menu as $key=>$value) {
            foreach ($link as $val) {
                if($val['parent_id']==$value['id'])
                    $menu[$key]['find'][] = $val;
            }
        }
        
        foreach ($menu as $key=>$value) {
            if($value['mark']=='' || !isset($value['find'])) {
                unset($menu[$key]);
            }
        }

        return $menu;
    }

    public static function getMenu($parent_id=0)
    {
        // 当前路由方法
        $method = '/'.Yii::$app->controller->module->requestedRoute;
        $result = [];
        $sql = "SELECT id,name,url,parent_id FROM `pro_menu` where parent_id = $parent_id AND status=1 AND is_show=1 ORDER BY weight desc";
       // echo $sql;die;
        $query = Yii::$app->db->createCommand($sql)->queryAll();
        if($query){
            foreach($query as $val){
                $temp = [
                    'label' => $val['name'],
                    'icon'  => '', 
                    'url'   => trim($val['url'])==''?'#':$val['url'],
                ];
                
                $items = self::getMenu($val['id']);
                if($items){
                    foreach($items as &$v)
                    {
                        if(trim($v['url']) == $method)
                        {
                            $v['active'] = 'true';
                        }
                    }
                    $temp['items'] = $items;
                }
                $result[] = $temp;
            }
        }
        return $result;
    }


    /**
     * 获取权限内可访问的菜单 ，仅限两级
     * @author lijing
     * @date 2017-08-01
     */
    public function access($userid)
    {
        // 当前路由方法
        $method = '/'.Yii::$app->controller->module->requestedRoute;
        $user_group = \backend\models\User::find()->select(['gid'])->where(['id' => $userid])->asArray()->one();
        $channel = Yii::$app->redis->get('channel_'.Yii::$app->user->getIdentity()->id);
        if(!empty($user_group['gid']))
        {
            $group = \backend\models\Group::find()->select(['mid','resource'])->where(['id' => $user_group['gid']])->asArray()->one();
            $module = explode(',', $group['mid']);
            // var_dump($module);die;
            if(!empty($module))
            {
                $link = \backend\models\Menu::find()->select(['url','name','parent_id'])->where(['id' => $module,'is_show' => 1, 'status'=>1])->asArray()->orderBy('weight DESC')->all();

                $access = \backend\models\Menu::find()->select(['url','name','parent_id'])->where(['id' => $module, 'status'=>1])->asArray()->orderBy('weight DESC')->all();

                $menu = \backend\models\Menu::find()->where(['parent_id' => 0, 'status'=>1])->asArray()->orderBy('weight DESC')->all();

                foreach ($access as $value) {
                    $accessarr['access'][] = $value['url'];
                }
                $accessarr['access'][] = '/index/index'; //默认的首页都是可以访问的


                $group['resource'] = trim($group['resource'], ',');
                //添加可访问的资源
                /***添加资源权限的管理，修补bug--添加当前登录的用户所创建的资源 ====结束***/

                // 目前只支持两级的菜单
                $access_menu = $check_menu = [];
                foreach ($menu as $key=>$value)
                {
                    $access_menu[$key] = [];
                    $access_menu[$key]['label'] = $value['name'];
                    $access_menu[$key]['icon']  = 'fa fa-circle-o';
                    $access_menu[$key]['url']   = trim($value['url'])==''?'#':$value['url'];
                    $access_menu[$key]['items'] = [];
                    $check_menu[$key] = false;
                    foreach ($link as $kk => $val)
                    {
                        if($val['parent_id']==$value['id'])
                        {
                            $check_menu[$key] = true;
                            // $menu[$key]['find'][] = $val;
                            $access_menu[$key]['items'][$kk] = [];
                            $access_menu[$key]['items'][$kk]['label'] = $val['name'];
                            $access_menu[$key]['items'][$kk]['icon'] = '';
                            $access_menu[$key]['items'][$kk]['url'] = trim($val['url'])==''?'#':$val['url'];
                            // 菜单展开
                            if(trim($access_menu[$key]['items'][$kk]['url'])==$method)
                            {
                                $access_menu[$key]['items'][$kk]['active'] = 'true';
                            }
                        }

                    }

//                    if ($value['mark']=='' || 0==count($access_menu[$key]['items'])) {
//                        unset($access_menu[$key]);
//                    }
                    if($check_menu[$key] == false)
                    {
                        unset($access_menu[$key]);
                    }
                }

                $accessarr['menu'] = $access_menu;
                return $accessarr;
            }
        }
        return array();
    }


//    public function access($userid) {
////        $groupsql = "select role_id from admins where id=$userid";
////        $group = Yii::$app->db->createCommand($groupsql)->queryOne();
//
//        $group = \backend\models\User::find()->select(['gid'])->where(['id' => $userid])->asArray()->one();
//
//        $id = $group['gid'];
//        if(!empty($id))
//        {
////            $modulesql = "select menu_id from role where id=$id";
////            $module = Yii::$app->db->createCommand($modulesql)->queryOne();
//
//            $module = \backend\models\Group::find()->select(['mid'])->where(['id' => $id])->asArray()->one();
//
//            $module = explode(',', $module['mid']);
//            if(!empty($module))
//            {
////                $linksql = "select url,mark,name,parent_id from menu where id in($module) and display=1";
////                $link = Yii::$app->db->createCommand($linksql)->queryAll();
//
//                $link = \backend\models\Menu::find()->select(['url','name','parent_id'])->where(['id' => $module,'is_show' => 1])->asArray()->all();
//
////                $accesssql = "select url,mark,name,parent_id from menu where id in($module)";
////                $access = Yii::$app->db->createCommand($accesssql)->queryAll();
//
//                $access = \backend\models\Menu::find()->select(['url','name','parent_id'])->where(['id' => $module])->asArray()->all();
//
//
//                $menu = \backend\models\Menu::find()->where(['parent_id' => 0])->asArray()->all();
//
//                foreach ($access as $value) {
//                    $accessarr['access'][] = $value['url'];
//                }
//
//                foreach ($menu as $key=>$value) {
//                    foreach ($link as $val) {
//                        if($val['parent_id']==$value['id'])
//                            $menu[$key]['find'][] = $val;
//                    }
//                }
//
//                foreach ($menu as $key=>$value) {
//                    if($value['mark']=='' || !isset($value['find'])) {
//                        unset($menu[$key]);
//                    }
//                }
//
//                $accessarr['menu'] = $menu;
//                return $accessarr;
//            }
//        }
//        return array();
//    }

    /***
     * 添加日志
     */
    public static function addlog($name, $content, $url)
    {
        $userlog = new UserLog();
        $userlog->add($name, $content, $url);
    }

    /**
     * 生成json数据
     */
    public static function make_json($data, $code = 200, $msg = '')
    {
        echo json_encode(['code' => $code, 'data' => $data, 'msg' => $msg]);
    }

}